package org.xbzheng.restful_study.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.xbzheng.restful_study.model.Card;
import org.xbzheng.restful_study.service.CardService;
import org.xbzheng.restful_study.util.ResponseEntity;

import java.util.List;

/**
 * @Created by szheng on 2016/11/1.
 */
@Controller
@RequestMapping("/card")
public class CardController extends BaseController{
    @Autowired
    private CardService cardService;

    @Autowired
    private SimpMessagingTemplate template;

    @RequestMapping("/create")
    @ResponseBody
    public String create(@RequestBody final Card card){
        final Card result = cardService.createCard(card);

        if(result != null){
            template.convertAndSend("/topic/card/create", result);
            return "true";
        }
        return "false";
    }

    @RequestMapping("/cards")
    public ResponseEntity getRoomCards(final int roomId){
        List<Card> cards = null;
        try{
            cards = cardService.findCardByRoom(roomId);
        }catch (Exception e){
            return getResult(500, e.getMessage());
        }
        return getResult(cards.toArray());
    }
}
